package com.kjtpay.design_pattern.interpreter;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.kjtpay.design_pattern.R;
import com.kjtpay.design_pattern.flyweight.FlyweightActivity;

public class InterpreterActivity extends AppCompatActivity {

    public static void launch(Context context) {
        if (null != context) {
            Intent intent = new Intent();
            intent.setClass(context, InterpreterActivity.class);
            if (!(context instanceof Activity)) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            }
            context.startActivity(intent);
        }
    }

    TextView textViewBefore;
    TextView textViewAfter;
    String before;
    String after;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_interpreter);
        setTitle("解释器模式");

        textViewBefore = findViewById(R.id.textViewBefore);
        textViewAfter = findViewById(R.id.textViewAfter);

        interpreter();
    }

    private void interpreter() {
        before = "T 500 O 2 E 0.5 G 0.5 A 3 E 0.5 G 0.5 D 3 E 0.5 G 0.5 A 0.5 O 3 C 1 O 2 A 0.5 G 1 C 0.5 E 0.5 D 3";
        textViewBefore.setText(before);
        after = "";
        PlayContext playContext = new PlayContext();
        playContext.playText = before;
        Expression expression = null;

        try {
            while (playContext.playText.length() > 0) {
                String string = playContext.playText.substring(0, 1);
                switch (string) {
                    case "O":
                        expression = new Scale();
                        break;
                    case "T":
                        expression = new Speed();
                        break;
                    case "C":
                    case "D":
                    case "E":
                    case "F":
                    case "G":
                    case "A":
                    case "B":
                        expression = new Note();
                        break;
                    default:
                        // 什么也不做
                        break;
                }
                if (null != expression) {
                    expression.interpret(playContext);
                    after += expression.getResult() + " ";
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        textViewAfter.setText(after);
    }
}